package com.ruoyi.framework.web.service;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.entity.WMember;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.*;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;
import com.ruoyi.framework.web.domain.WechatMPLoginParams;
import com.ruoyi.framework.web.domain.WechatMPNumberParams;
import com.ruoyi.kit.setting.WechatPaymentSetting;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.weiriya.domain.WSetting;
import com.ruoyi.weiriya.service.IWMemberService;
import com.ruoyi.weiriya.service.IWSettingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录校验方法
 *
 * @author lynn
 */
@Slf4j
@Component
public class SysLoginService {
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private IWMemberService memberService;

    @Autowired
    private IWSettingService settingService;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {
        // 验证码校验
        validateCaptcha(username, code, uuid);
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid) {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled) {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            String captcha = redisCache.getCacheObject(verifyKey);
            redisCache.deleteObject(verifyKey);
            if (captcha == null) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            if (!code.equalsIgnoreCase(captcha)) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
    }

    /**
     * 登录前置校验
     *
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }


    public String getTokenByOpenId(String openId) {

        UserDetails userDetails = userDetailsService.loadUserByUsername(openId);
        LoginUser loginUser = (LoginUser) userDetails;
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 小程序绑定
     *
     * @param params 绑定参数
     * @return 令牌
     */
    public String mpBind(WechatMPLoginParams params) {
        JSONObject connect = getConnect(params.getCode());

        String openId = connect.getString("openid");

//        String openId = "oU6J25KVLKjS3QKNtlIKFo88PQbw";

        LambdaQueryWrapper<WMember> wMemberQueryWrapper = new LambdaQueryWrapper<>();
        wMemberQueryWrapper.eq(WMember::getUserName, params.getUsername());

        WMember wMember = memberService.getOne(wMemberQueryWrapper);
        if (wMember == null) {
            wMember = new WMember();
            wMember.setNickName(params.getNickname());
            wMember.setOpenId(openId);
            wMember.setUserName(params.getUsername());
            wMember.setPassword(StringUtils.isNotBlank(params.getPassword()) ? SecurityUtils.encryptPassword(params.getPassword()) : null);
            wMember.setCreateTime(new Date());
            wMember.setCreateBy("1");
            memberService.saveOrUpdate(wMember);
        } else {
            boolean isChange = false;
            if (StringUtils.isNotBlank(params.getNickname())) {
                wMember.setNickName(wMember.getNickName());
                isChange = true;
            }
            if (StringUtils.isNotBlank(params.getAvatar())) {
                wMember.setAvatar(wMember.getAvatar());
                isChange = true;
            }
            if (StringUtils.isBlank(wMember.getOpenId())) {
                wMember.setOpenId(openId);
                isChange = true;
            }
            if (isChange) {
                memberService.updateById(wMember);
            }
            if (wMember.getStatus() == 2)
                throw new ServiceException("账号违规，请联系管理员！");
            if (StringUtils.isNotBlank(wMember.getPassword())) {
                if (!SecurityUtils.matchesPassword(params.getPassword(), wMember.getPassword()))
                    throw new ServiceException("密码错误！");
            }
        }

        return getTokenByOpenId(openId);
    }


    /**
     * 通过微信返回等code 获取openid 等信息
     *
     * @param code 微信code
     * @return 微信返回的信息
     */
    public JSONObject getConnect(String code) {
//        YhMp yhMp = yhMpMapper.getYhMpSetting();
        WechatPaymentSetting wechatPaymentSetting = getWechatPaymentSetting();
        // todo 登录用appID
        String url = "https://api.weixin.qq.com/sns/jscode2session?" +
                "appid=" + wechatPaymentSetting.getAppId() + "&" +
                "secret=" + wechatPaymentSetting.getAppSecret() + "&" +
                "js_code=" + code + "&" +
                "grant_type=authorization_code";
        String content = HttpUtils.doGet(url, "UTF-8", 100, 1000);

        return JSON.parseObject(content);
    }

    public WechatPaymentSetting getWechatPaymentSetting() {


        WSetting setting = settingService.getById("WECHAT");
        String settingValue = setting.getSettingValue();
        WechatPaymentSetting wechatPaymentSetting = JSONUtil.toBean(settingValue, WechatPaymentSetting.class);
        return wechatPaymentSetting;
    }

    public Object getMpUserName(WechatMPNumberParams params) throws Exception {

        WechatPaymentSetting wechatPaymentSetting = getWechatPaymentSetting();
        // 获取token
//        String token_url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", "wxd4887d676c7ee0d6", "c054f42b433ffc6d3399ac9498984d41");
        String token_url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", wechatPaymentSetting.getAppId(), wechatPaymentSetting.getAppSecret());
        JSONObject token = JSON.parseObject(HttpUtil.get(token_url));// 使用前端code获取手机号码 参数为json格式

        log.error("token```````````",token);

        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + token.getString("access_token");
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("code", params.getCode());
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(paramMap, headers);
        System.out.println(httpEntity);
        RestTemplate template = new RestTemplate();
        ResponseEntity<Object> response = template.postForEntity(url, httpEntity, Object.class);

        log.error("token```````````",JSON.toJSONString(response));
        String s = JSON.toJSONString(response.getBody());

        log.error("11111111111111111111111111111111",s);

        JSONObject body = JSONObject.parseObject(s);
        JSONObject phone_info = body.getJSONObject("phone_info");
        String phoneNumber = phone_info.getString("phoneNumber");

        Map<String, Object> map = new HashMap<>();
        map.put("phoneNumber", phoneNumber);
        WMember one = memberService.getOne(new LambdaQueryWrapper<WMember>()
                .eq(WMember::getUserName, phoneNumber));
        map.put("havePwd",  StringUtils.isNotNull(one) && StringUtils.isNotBlank(one.getPassword()));
        map.put("haveNickName",  StringUtils.isNotNull(one) && StringUtils.isNotBlank(one.getNickName()));
        map.put("haveAvatar",  StringUtils.isNotNull(one) && StringUtils.isNotBlank(one.getAvatar()));
        return map;
    }

}
